<script setup lang='ts'>
import type { DataTableRowKey } from 'naive-ui'
import {
  NButton, NCard, NDataTable, NInput, NLayout, NLayoutContent, NLayoutHeader, NModal, NSelect, NSpace, useMessage,
} from 'naive-ui'
import { computed, h, ref, watch } from 'vue'
import axios from 'axios'
import { SvgIcon } from '@/components/common'
// import OutlineGeneration from '../outlineGeneration/index.vue'

// 假设每篇文章有一个唯一的ID作为键
interface Article {
  articleId: string
  articleTitle: string
  articleYear: string
  articleAuthors: string
  articleLanguage: string
  articleText: string
}
// const articles = ref([]);
const articles = ref<Article[]>([])
const showAbstractModal = ref(false)
const showOutlineModal = ref(false)
const currentAbstract = ref('')
// const searchQuery = ref('');
const searchQuery = ref<string>('')
const checkedRowKeys = ref<DataTableRowKey[]>([])
const selectedArticleIds = ref<string[]>([])

const showCustomDateModal = ref(false)
const dateFilter = ref('')
const startYear = ref(null)
const endYear = ref(null)

// 大纲模态框相关

const inputCount = ref(3) // 默认输入框数量为三个
const reportTitle = ref('')
const reportOutlines = ref(new Array(inputCount.value).fill(''))
// const reportOutlines = ref<string[]>([]);
const options = ref([
  { label: '单篇观点抽取', value: 'single' },
  { label: '多篇报告生成', value: 'multiple' },
])

// 定义一个响应式变量来存储选中的值
const selectedOption = ref('')

// 定义文章列表正文部分是否展开
const expandedStates = ref<{ [key: string]: boolean }>({})

// 定义 columns
const columns = [
  {
    type: 'selection',
    width: '50px',
  },
  {
    key: 'detail',
    width: '100%',
    render(row: Article) {
      // 切换文章展开状态的函数
      const toggleExpand = () => {
        expandedStates.value[row.articleId] = !expandedStates.value[row.articleId]
      }
      return [
        h('div', { style: { color: 'green' } }, `${row.articleTitle}`),
        h('div', {
          style: { display: 'flex', alignItems: 'center', gap: '10px' },
        }, [
          h('div', {
            style: {
              display: 'inline-block',
              padding: '2px 8px',
              borderRadius: '10px',
              backgroundColor: '#f0f0f0',
            },
          }, `${row.articleYear}`),
          h('div', { style: { color: 'grey' } }, `${row.articleAuthors}`),
        ]),
        // 根据展开状态动态添加或移除 three-line-clamp 类
        h('div', {
          class: { 'three-line-clamp': !expandedStates.value[row.articleId] },
          onClick: toggleExpand,
          style: { cursor: 'pointer' }, // 可选，使其看起来可以点击
        }, `${row.articleText}`),
        // h('div', {}, `${row.articleId}`)
      ]
    },
  },
]

// 为每行定义一个唯一键
const rowKey = (row: Article) => row.articleId

// 处理复选框状态变化
// const handleCheck = (keys: DataTableRowKey[]) => {
//   checkedRowKeys.value = keys;
// };
// 更新选中的文章ID
const handleCheck = (checkedRowKeys: string[]) => {
  selectedArticleIds.value = checkedRowKeys
}

watch(dateFilter, (newValue) => {
  if (newValue === 'custom')
    showCustomDateModal.value = true
})

const fetchArticles = async () => {
  try {
    console.log('打印keyWord', searchQuery.value)
    const response = await axios({
      method: 'post',
      // baseURL:'http://10.129.40.245:8080',
      baseURL: 'http://10.29.138.250:8080',
      url: '/findArticleByKeyword',
      data: {
        keyWord: searchQuery.value,
        pageNo: 1,
        pageSize: 10,
      },
    })
    articles.value = response.data
  }
  catch (error) {
    console.error('Error fetching articles:', error)
    articles.value = []
  }
}

const filteredArticles = computed(() => {
  if (!searchQuery.value)
    return articles.value

  return articles.value.filter(article =>
    article.articleTitle.includes(searchQuery.value),
  )
})

const message = useMessage()

const cancelCallback = () => {
  message.success('Cancel')
}

// const submitCallback = () => {
//   message.success('Submit')
//   console.log('模态框确认生成操作');
//   // 根据需要进行操作，比如console测试
// }

const handleGenerateClick = () => {
  if (selectedOption.value === 'multiple') {
    showOutlineModal.value = true
  }
  else {
    // 这里可以放置“单篇观点抽取”时的逻辑，如果没有则不执行任何操作
    // 例如，显示一个消息或执行特定逻辑
    // message.info('单篇观点抽取逻辑执行');
  }
}

// const handleOutlineSubmit = (outlineData) => {
//   console.log("hhhhh")
//   const postData = {
//     articleList: checkedRowKeys.value.map(key => {
//       const article = articles.value.find(article => article.articleId === key);
//       return {
//         articleTitle: article.articleTitle,
//         articleText: article.articleText
//       };
//     }),
//     userTitle: outlineData.reportTitle,
//     userOutline: outlineData.reportOutlines
//   };
//   console.log(postData)
//   // 在这里发送POST请求
//   axios.post('您的接口URL', postData)
//     .then(response => {
//       // 处理成功响应
//       console.log('Success:', response);
//     })
//     .catch(error => {
//       // 处理错误
//       console.error('Error:', error);
//     });
// };

const submitCallback = async () => {
  // 过滤选中的文章，基于过滤后的文章列表
  const selectedArticles = filteredArticles.value.filter(article => selectedArticleIds.value.includes(article.articleId))

  // 准备要发送的数据
  const postData = {
    doc_list: selectedArticles.map(article => ({
      doc_title: article.articleTitle,
      doc_content: article.articleText,
    })),
    user_title: reportTitle.value,
    user_outline: reportOutlines.value,
    user_keywords: '核武器、核态势、全球核武器发展、中国、美国、朝鲜、俄罗斯、中美',
  }

  // 设置请求头
  const config = {
    headers: {
      'Content-Type': 'application/json',
    },
  }

  // 发送POST请求
  try {
    // const response = await axios.post('/api/endpoint', postData);
    // console.log('Submit Success:', response);
    console.log(postData)
    const response = await axios.post('http://10.112.203.120:20618/multi_doc_generate', postData, config)
    // const response = await axios.post('http://localhost:20618/multi_doc_generate', postData, config);
    console.log('Data submitted successfully:', response.data)
    // 成功后的操作...
  }
  catch (error) {
    console.error('Submit Error:', error)
    console.error('Error submitting data:', error)
    // 错误处理...
  }
}

function decreaseInputCount() {
  if (inputCount.value > 1)
    inputCount.value--
}

function increaseInputCount() {
  inputCount.value++
}
watch(inputCount, (newCount, oldCount) => {
  if (newCount > oldCount) {
    for (let i = oldCount; i < newCount; i++)
      reportOutlines.value.push('')
  }
  else {
    reportOutlines.value = reportOutlines.value.slice(0, newCount)
  }
})

watch(reportOutlines, (newVal) => {
  console.log('reportOutlines changed:', newVal)
})
</script>

<template>
  <NLayout>
    <!-- 搜索框 -->
    <NLayoutHeader>
      <NCard>
        <div class="flex items-center justify-between space-x-2">
          <NInput v-model:value="searchQuery" placeholder="请输入关键词" class="input-with-select" />
          <NButton type="primary" @click="fetchArticles">
            <template #icon>
              <SvgIcon icon="ri:search-line" />
            </template>
          </NButton>
        </div>
      </NCard>
    </NLayoutHeader>
    <NLayout has-sider>
      <!-- <NLayoutSider width="20%">
        <NCard>
          时间筛选
          <NRadioGroup v-model="dateFilter" name="time">
            <NSpace vertical>
              <NRadio label="all">时间不限</NRadio>
              <NRadio label="2024">2024年以来</NRadio>
              <NRadio label="2022">2022年以来</NRadio>
              <NRadio label="2020">2020年以来</NRadio>
              <NRadio label="custom">自定义时间范围</NRadio>
            </NSpace>
          </NRadioGroup>

          <NModal v-model:show="showCustomDateModal" title="选择时间范围">
            <NSpace vertical>
              <NInputNumber v-model:value="startYear" placeholder="开始年份" min="1900" max="2099" />
              <NInputNumber v-model:value="endYear" placeholder="结束年份" min="1900" max="2099" />
            </NSpace>
          </NModal>
        </NCard>
        <NCard>
          排序选择
          <NRadioGroup>
            <NSpace vertical>
              <NRadio label="default">默认排序</NRadio>
              <NRadio label="asc">时间升序</NRadio>
              <NRadio label="desc">时间降序</NRadio>
            </NSpace>
          </NRadioGroup>
        </NCard>
        <NCard>
          语言选择
          <NRadioGroup>
            <NSpace vertical>
              <NRadio label="all">所有语言</NRadio>
              <NRadio label="cn">中文</NRadio>
              <NRadio label="en">英文</NRadio>
            </NSpace>
          </NRadioGroup>
        </NCard>
      </NLayoutSider> -->

      <NLayoutContent>
        <NCard>
          <div class="flex items-center justify-end space-x-2">
            <NSelect v-model:value="selectedOption" style="width: 30%" :options="options" />
            <NButton type="primary" @click="handleGenerateClick">
              <template #icon>
                <!-- SvgIcon或其他图标 -->
                <a>生成</a>
              </template>
            </NButton>
          </div>

          <!-- <NModal v-model:show="showOutlineModal" preset="dialog" title="报告大纲生成" positive-text="确认生成" negative-text="取消"
            @positive-click="submitCallback" @negative-click="cancelCallback" @submitOutline="handleOutlineSubmit"
            style="width: 30%">
            <OutlineGeneration @closeModal="showOutlineModal = false" />
          </NModal> -->
          <NModal
            v-model:show="showOutlineModal" preset="dialog" title="报告大纲生成" positive-text="确认生成" negative-text="取消"
            style="width: 30%" @positive-click="submitCallback" @negative-click="cancelCallback"
          >
            <!-- <OutlineGeneration @closeModal="showOutlineModal = false" /> -->
            <NCard>
              <NSpace vertical>
                <div>请输入报告标题</div>
                <NInput v-model:value="reportTitle" type="text" placeholder="请输入报告标题" />
                <NSpace>
                  <div>可修改增删大纲</div>
                  <!-- “减”按钮 -->
                  <NButton @click="decreaseInputCount">
                    -
                  </NButton>
                  <!-- “加”按钮 -->
                  <NButton @click="increaseInputCount">
                    +
                  </NButton>
                </NSpace>

                <!-- 使用 v-for 根据 inputCount 动态生成输入框 -->
                <NInput
                  v-for="index in inputCount" :key="index" v-model:value="reportOutlines[index - 1]" type="text"
                  placeholder="请输入报告大纲内容" clearable
                />
              </NSpace>
            </NCard>
          </NModal>
        </NCard>

        <!-- 文章列表 -->
        <!-- 文章列表表格 -->
        <NCard>
          <!-- <div>共检索出6篇文章</div> -->

          <NDataTable
            :columns="columns" :data="filteredArticles" :row-key="rowKey"
            @update:checked-row-keys="handleCheck"
          />
        </NCard>
      </NLayoutContent>
    </NLayout>
  </NLayout>
  <!-- 摘要弹窗 -->
  <NModal v-model:show="showAbstractModal" title="文章摘要" :width="600">
    <NCard style="width: 600px" title="文章摘要" :bordered="false" size="huge" role="dialog" aria-modal="true">
      <p>{{ currentAbstract }}</p>
      <template #footer>
        <NSpace>
          <NButton type="primary" @click="showAbstractModal = false">
            关闭
          </NButton>
        </NSpace>
      </template>
    </NCard>
  </NModal>
</template>

<style>
/* 限制文本显示为三行 */
.three-line-clamp {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
